<!-- 业务类型入案、出案 -->
<template>
  <div id="tr-jz-money-bar"></div>
</template>

<script setup>
import { onMounted, reactive, watch } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  data: { type: Object, default: () => { } },
});

// const gridModel = () => {
//   return {
//     left: '55%',
//     right: '5%',
//     top: '20%',
//     bottom: "25%"
//   };
// };

const xAxisModel = () => {
  return {
    type: 'category',
    gridIndex: 0,
    data: [],
    axisLabel: {
      interval: 0 // 强制显示所有标签
    },
    axisTick: {
      length: 0,
    },
  };
};

const ywhjModel = () => {
  return {
    type: 'category',
    gridIndex: 0,
    offset: 10,
    data: [
      {
        value: '',
        textStyle: {
          fontSize: 14,
        }
      }
    ],
    axisLabel: {
      margin: -7,
      backgroundColor: '#FFFFFF',
      padding: [0, 5]
    },
    axisTick: {
      length: 0,
    },
    axisLine: {
      lineStyle: {
        color: '#8c5738'
      },
      symbol: ['arrow', 'arrow']
    },
    position: 'top',
  };
};

const seriesModel = () => {
  return {
    name: '入库',
    xAxisIndex: 0,
    yAxisIndex: 0,
    data: [7, 14, 14, 7, 5],
    barWidth: 30,
    type: 'bar',
    barGap: '20%',
    barCategoryGap: '5%'
  };
};

const yAxisFirstModel = () => {
  return {
    type: 'value',
    name: '费用（万元）',
    axisLabel: {
      interval: 0,
      show:false
    },
    gridIndex: 0,
    axisLine: {
      show: true,
      symbol: ['none', 'triangle']
    },
    splitLine: {
      show: false
    }
  };
};

const yAxisOtherModel = () => {
  return {
    show: true,
    gridIndex: 1,
    axisLine: {
      show: true,
      symbol: ['none'],
      lineStyle: {
        type: 'dashed'
      },
    },
    type: 'value',
    splitLine: {
      show: false
    },
    axisLabel: {
      formatter: ''
    }
  };
};

const option = reactive(
  {
    legend: {
      orient: 'vertical',
      x: 'left',
      y: 'bottom',
      padding: [0, 45, 25, 0],
      data: ['拟收费', '已收费'],
    },
    grid: [],
    tooltip: {
      trigger: 'axis',
      // axisPointer: {
      //   type: 'shadow', //line
      //   label: {
      //     show: true,
      //     color: "#000"
      //   }
      // }
    },
    xAxis: [],
    yAxis: [],
    series: []
  }
);
let myChart = null;

// const loadGrid = (data) => {
//   let grid = [];
//   let total = data.reduce((pre, cur) => {
//     let lengthValue = cur.project_count_and_amount_for_ywlx_dtolist.length > 0 ? cur.project_count_and_amount_for_ywlx_dtolist.length : 1;
//     return pre + lengthValue;
//   }, 0);
//   console.log(total, 'total')
//   let width = 80 / total;
//   let leftTemp = 5;
//   data.forEach(item => {
//     let gridItem = gridModel();
//     let lengthValue = item.project_count_and_amount_for_ywlx_dtolist.length > 0 ? item.project_count_and_amount_for_ywlx_dtolist.length : 1;
//     gridItem.left = leftTemp + '%';
//     gridItem.width = width * lengthValue + '%';
//     leftTemp += width * lengthValue;
//     grid.push(gridItem);
//   })
//   return grid;
// }

// 宽度配置映射表
const manualWidthConfig = {
  '前期咨询': 15,
  '地理信息数据服务': 10,
  '规划编制及专项评估': 15,
  '用地报批': 20,
  '土地供应': 10,
  '规划报建': 10,
  '规划条件核实及登记': 10
};
const loadGrid = (data) => {
  let grid = [];
  let leftTemp = 4;

  data.forEach((item) => {
    const widthPercent = manualWidthConfig[item.ywhj] || 10;

    grid.push({
      left: `${leftTemp}%`,
      width: `${widthPercent}%`,
      top: '25%',
      bottom: "5%",
      containLabel: true
    });

    leftTemp += widthPercent;
  });
  return grid;
};

const loadxAxis = (data) => {
  let xAxis = [];
  let ywhj = [];
  for (let i = 0; i < data.length; i++) {
    let ywhjItem = ywhjModel();
    ywhjItem.data[0].value = data[i].ywhj;
    ywhjItem.gridIndex = i;

    let xAxisItem = xAxisModel();
    xAxisItem.gridIndex = i;
    xAxisItem.data = data[i].project_count_and_amount_for_ywlx_dtolist.map(item => item.ywlx);

    if (ywhjItem.data[0].value.includes('前期咨询') && xAxisItem.data.length === 0) {
      xAxisItem.data = ['前期咨询']
    }
    if (ywhjItem.data[0].value === '地理信息数据服务') {
      xAxisItem.data = ['基础数据调查', '现状地形图测绘']
    }
    if (ywhjItem.data[0].value === '规划编制及专项评估') {
      xAxisItem.data = ['控制性详细规划', '城市设计', '城市更新方案编制']
    }
    if (ywhjItem.data[0].value === '用地报批') {
      xAxisItem.data = ['勘测定界', '集体土地确权', '违法用地测量', '用地报批']
    }
    if (ywhjItem.data[0].value === '土地供应') {
      xAxisItem.data = ['不动产权籍调查']
    }
    if (ywhjItem.data[0].value === '规划报建') {
      xAxisItem.data = ['技术审查', '放线']
    }
    if (ywhjItem.data[0].value === '规划条件核实及登记') {
      xAxisItem.data = ['验收']
    }

    // console.log('111', ywhjItem.data[0].value, xAxisItem.data)
    if (i === data.length - 1) {
      xAxisItem.axisLine = {
        symbol: ['none', 'triangle']
      }
    }

    ywhj.push(ywhjItem);
    xAxis.push(xAxisItem);
  }
  return [...xAxis, ...ywhj];
}

const loadyAxis = (data) => {
  let yAxis = [];
  for (let i = 0; i < data.length; i++) {
    if (i === 0) {
      let yAxisTemp = yAxisFirstModel();
      yAxisTemp.gridIndex = i;
      yAxis.push(yAxisTemp);
      continue;
    }

    let yAxisTemp = yAxisOtherModel();
    yAxisTemp.gridIndex = i;
    yAxis.push(yAxisTemp);
  }
  return yAxis;
}

function extractYsfValues(a, b) {
  // 创建映射：ywlx 字符串 -> ysf 值
  const ywlxMap = {};
  for (const obj of b) {
    ywlxMap[obj.ywlx] = obj.ysf;
  }

  // 根据数组a的顺序提取值，不存在则补0
  return a.map(key => ywlxMap[key] ?? 0);
}

function extractNsfValues(a, b) {
  // 创建映射：ywlx 字符串 -> ysf 值
  const ywlxMap = {};
  for (const obj of b) {
    ywlxMap[obj.ywlx] = obj.nsf;
  }

  // 根据数组a的顺序提取值，不存在则补0
  return a.map(key => ywlxMap[key] ?? 0);
}


const loadSeries = (data) => {
  let series = [];
  for (let i = 0; i < data.length; i++) {
    let raItem = seriesModel();
    raItem.name = '拟收费';
    raItem.data = data[i].project_count_and_amount_for_ywlx_dtolist.map(item => item.nsf);
    raItem.xAxisIndex = i;
    raItem.yAxisIndex = i;

    let caItem = seriesModel();
    caItem.name = '已收费';
    caItem.data = data[i].project_count_and_amount_for_ywlx_dtolist.map(item => item.ysf);
    caItem.xAxisIndex = i;
    caItem.yAxisIndex = i;

    if (data[i].ywhj === '前期咨询') {
      const arrays = ["前期咨询"]
      raItem.data = extractNsfValues(arrays, data[i].project_count_and_amount_for_ywlx_dtolist);
      caItem.data = extractYsfValues(arrays, data[i].project_count_and_amount_for_ywlx_dtolist);
    }

    if (data[i].ywhj === '地理信息数据服务') {
      const arrays = ['基础数据调查', '现状地形图测绘']
      raItem.data = extractNsfValues(arrays, data[i].project_count_and_amount_for_ywlx_dtolist);
      caItem.data = extractYsfValues(arrays, data[i].project_count_and_amount_for_ywlx_dtolist);
    }

    if (data[i].ywhj === '规划编制及专项评估') {
      const arrays = ['控制性详细规划', '城市设计', '城市更新方案编制']
      raItem.data = extractNsfValues(arrays, data[i].project_count_and_amount_for_ywlx_dtolist);
      caItem.data = extractYsfValues(arrays, data[i].project_count_and_amount_for_ywlx_dtolist);
    }

    if (data[i].ywhj === '用地报批') {
      const arrays = ['勘测定界', '集体土地确权', '违法用地测量', '用地报批']
      raItem.data = extractNsfValues(arrays, data[i].project_count_and_amount_for_ywlx_dtolist);
      caItem.data = extractYsfValues(arrays, data[i].project_count_and_amount_for_ywlx_dtolist);
    }

    if (data[i].ywhj === '规划报建') {
      const arrays = ['技术审查', '放线']
      raItem.data = extractNsfValues(arrays, data[i].project_count_and_amount_for_ywlx_dtolist);
      caItem.data = extractYsfValues(arrays, data[i].project_count_and_amount_for_ywlx_dtolist);
    }

    series.push(raItem);
    series.push(caItem);
  }
  return series;
}

const loadJZData = (data) => {
  option.grid = loadGrid(data);
  option.xAxis = loadxAxis(data);
  option.yAxis = loadyAxis(data);
  option.series = loadSeries(data);
  console.log(option);
}

watch(() => props, () => {
  console.log('watch', props.data)
  loadJZData(props.data);
  myChart.setOption(option);
}, { deep: true })

onMounted(() => {
  myChart = echarts.init(document.getElementById('tr-jz-money-bar'));
  myChart.setOption(option);
});
</script>

<style scoped></style>
